<?php
$path = drupal_get_path('module', 'go_view');
drupal_add_css($path . '/css/go_view.css');

function go_view_get_date($nid, $vid) {
	if($nid) {
		$entity_type = 'node';
		$bundle = 'govt_orders';
		$nid = $nid;
		my_db_change(1);
		$field_value_go_date = db_select('field_revision_field_go_date', 'f')
		->fields('f', array('entity_id', 'field_go_date_value'))
		->condition('entity_type', $entity_type)
		->condition('bundle', $bundle)
		->condition('entity_id', $nid, '=')
		->condition('revision_id', $vid, '=')
		->condition('deleted', 0)
		->execute()
		->fetchAllKeyed();
		my_db_change(0);
		return $field_value_go_date[$nid];
	}
}

function gos_title(){

	global $language;
	$dep_val = arg(2);

	//drupal_add_css(drupal_get_path('module', 'go_view') . '/css/go_view.css', array('group' => CSS_DEFAULT, 'every_page' => TRUE));
	$docheader = "<div id='viewmod_govtinterest' class='view-header'>" . get_govt_header( 'dept' ) ."</div>";

	db_set_active('cmsdb');


	$yourvalue = '1';
	$query = new EntityFieldQuery();
	$query->entityCondition('entity_type', 'node')
		  ->entityCondition('bundle', 'govt_orders')
		  ->propertyCondition('language', 'en')
		  ->propertyCondition('status', 1)
		  // ->propertyCondition('nid','11171','=')
		  // ->fieldCondition('field_go_depart', 'value', 'NULL', '!=')
		  ->fieldCondition('field_go_depart', 'value',$dep_val, '=')
		  ->fieldCondition('field_go_date', 'value', array('1970-01-01T00:00:00', '2014-04-31T00:00:00'), 'BETWEEN')
          ->fieldOrderBy('field_go_date','value','DESC')

		  //->fieldCondition('field_go_date', 'value', array('2011-03-01', '2011-03-31'), 'BETWEEN')
          //->fieldOrderBy('field_go_date', 'value', 'ASC')
		 // ->fieldCondition('field_go_date', 'value', '2011-01-06T00:00:00', '=')

		 // ->addMetaData('account', user_load(1))
		  ->pager(20,0);


	$result = $query->execute();

	//->pager(20);
	if (isset($result['node'])) {
  $news_items_nids = array_keys($result['node']);
  $items = entity_load('node', $news_items_nids);

  /*print_r(entity_view('node', $items));
  $quotes = array();*/

 /* return array(
      'gos_title_list' => theme('gos_title_list', array('items' => $quotes)),
      //'pager' => theme('pager', $query->pager),
    );*/
  //print "<pre>"; print_r($items); print "</pre>";die;
}
	db_set_active('default');
	//$output = theme('gos_title_list', array('items' => $news_items));
	$output = $docheader. theme('gos_title_list', array('items' => $items)). theme('pager');
	return $output;
}

/**
 * Function for govt_department_details()
 * @return string
 */
function govt_department_details(){

	global $language,$base_url;
	$dep_val = arg(2);
	$output = '';
	//print_r($language);
		db_set_active('cmsdb');
		//drupal_add_css(drupal_get_path('module', 'go_view') . 'css/go_view.css');
		$op = "<div id='viewmod_govtinterest' class='view-header'>" . get_govt_header( 'dept' ) ."</div>";
		$op .= "<div class='go_view'><div class='back_btn'><span>" .l(t('Back'),'go_view/dept'). "</span></div>";
		//print_r($result);
		/*
			$qry = db_select('node','n');
				$qry->addField('n','title');
				$qry->addField('n','nid');
				$qry->addField('n','vid');
				$qry->addJoin('INNER','field_data_field_go_abstract','ga', 'n.nid = ga.entity_id');
				$qry->addJoin('INNER','field_data_field_go_date','gda', 'n.nid = gda.entity_id');
				$qry->addJoin('INNER','field_data_field_go_depart','gd', 'n.nid = gd.entity_id');
				$qry->addJoin('INNER','depart_mst','d','d.dep_id = CAST(gd.field_go_depart_value AS INT)');
				$qry->addJoin('INNER','field_data_field_go_available_file','gf','n.nid = gf.entity_id');
				$qry->addJoin('INNER','file_usage','fu','fu.id = n.nid');
				$qry->addJoin('INNER','file_managed','fm','fm.fid = fu.fid');
				$qry->addField('ga','field_go_abstract_value');
				$qry->addField('gd','field_go_depart_value');
				$qry->addField('gda','field_go_date_value');
				$qry->addField('fm','uri');
				$qry->addField('fm','filesize');
				$qry->condition('n.status', '1');
				$qry->condition('d.dep_id', $dep_val,'=');
				$qry->condition('n.language', array($GLOBALS['language']->language),'=');
				$qry->orderby('gda.field_go_date_value','DESC');


				$result=$qry->extend('PagerDefault')->limit(20)->execute();
				*/
				$lan = array($GLOBALS['language']->language);

				$query = new EntityFieldQuery();
				$query->entityCondition('entity_type', 'node')
				->entityCondition('bundle', 'govt_orders')
				->propertyCondition('status',1)
				->fieldCondition('field_go_depart', 'value', $dep_val, '=')
				->propertyCondition('language', array($GLOBALS['language']->language, ''),'IN')
				->fieldOrderBy('field_go_date', 'value', 'DESC');
				//->pager(20);
				$result = $query->execute();

				if (isset($result['node'])) {
					$news_items_nids = array_keys($result['node']);
				}

				//print "<pre>"; print_r(node_load(48770, 172755, TRUE)); print "</pre>";
				//print "<pre>"; print_r($news_items_nids); print "</pre>"; exit;

			db_set_active('default');

			$per_page = 20;
			$current_page = pager_default_initialize(count($news_items_nids), $per_page);
			$chunks = array_chunk($news_items_nids, $per_page, TRUE);

			$kbyte = '';
    		$curdept = '';
    		$go_year = '';
    		$titl = '';

		 foreach($chunks[$current_page] as $key=>$nid) {
		 //foreach($news_items_nids as $key=>$nid) {
		 	my_db_change(1);
		 	$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
		 	$res = node_load($nid, $vid);
		 	$go_date = go_view_get_date($nid, $vid);
		 	my_db_change(0);

		//print "<pre>"; print_r($res); print "</pre>";

		$dept =  $res->field_go_depart['und']['0']['value'];
		$deptName = get_govt_dept_names($dept);
		$abstract =  $res->field_go_abstract['und'][0]['value'];
		$filepath = $res->field_go_available_file['und'][0]['uri'];
		$filesize = $res->field_go_available_file['und'][0]['filesize'];
		$title = $res->title;


		$go_date_check = date('F d, Y',strtotime($go_date));
		$goYear = date("Y", strtotime($go_date));


	if(empty($filepath)){
							$wrapper = file_stream_wrapper_get_instance_by_uri($filepath);

							if($wrapper == true){
								$filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($filepath);
							}
							$icon = '';
					}else{
						  	$icon = get_pdf_icon($filesize)	;
						 	//$filepath = $baseurl.$contentlist->filepath;
							$wrapper = file_stream_wrapper_get_instance_by_uri($filepath);

							if($wrapper == true){
								$filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($filepath);

							}//$department= $contentlist -> dept_name;

					}

					if($filesize != 0){

							$kb = ceil($filesize/1024);
						$kbyte= $kb.KB;
						if($kb >1024) {
						  $kb = ceil($kb/1024);
						  $kbyte= $kb.MB;
						}
					}

		if( $goYear != $go_year )		{
					$go_year = $goYear;
					$divOutput1 = "<div class='res_dept go_depart' ><strong>Year : " .  $goYear  . "</strong></div>";
				}
				else		{
					$divOutput1 = '';
				}

		if( $deptName != $curdept )		{
			$curdept = $deptName;
			$divOutput =   t(ucfirst($deptName)) ;

		}
		else{
			$divOutput = '';
		}


	if($title != $titl){
	$titl = $title;
	$op .= "<div class='go_box'>
				<div class='res_dept go_depart'><span><strong>" .$divOutput. "</strong></span></div>
								<div class='go_title'>" .$divOutput1. "</div>
				<div>". $res->nid ." </div>
				<div class='go_abstract'><a target='_blank' href='http://cms.tn.gov.in/tncms_latest/" .$filepath. "'>"
				.$title . " Dt: ". $go_date_check. "<span class='kb'>".$icon. $kbyte. "</span></a>"
				   .$abstract. "</div>
			</div>";
		}

	}


		$output .= "<div id='result_go' class='result_inner'>";
		$output .= $op;
		//$output .= "<div class='clr'></div></div>";

		//return $output.theme('pager');
		return $output.theme('pager', array('quantity',count($news_items_nids)));
	//theme('gos_atoz', array('items' => $items)). theme('pager');
}



function Govt_AtoZ_letters( $sel )
{
	global $base_url,$language;
	$linkOp = '';
	/*if (is_mobile_browser()){
		$node = set_for_mobile_browser();
		drupal_add_css(drupal_get_path('module', 'go_view') . '/go_view_mobile.css');
		return theme('mobile_menu_theme', $node);
	}else {*/
		//drupal_add_css(drupal_get_path('module', 'go_view') . '/go_view.css');
	//}

	//$modPath = drupal_get_path('module', 'go_view');
	drupal_set_title(t('Government of Tamil Nadu')." : ".t('Government Orders'));

	$listArr = array( "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "All" );
	foreach( $listArr as $key => $val )	{
		if( $sel == $val || strtolower( $sel ) == strtolower( $val ) )		{
			$selected = 'view_head_sel';

		}else{
			$selected = 'view_head_nonsel';

		}
		if($language->language == 'en'){
			$linkOp .= "<a href='" . $base_url . "/go_view/atoz/" . $val . "' class='" . $selected . "'>" . $val . "</a>&nbsp;&nbsp;";
		}
		else{
			$linkOp .= "<a href='" . $base_url . "/ta/go_view/atoz/" . $val . "' class='" . $selected . "'>" . $val . "</a>&nbsp;&nbsp;";
		}

	}

	return $linkOp;
}

/**
 * Function for govt_atoz()
 * @return string
 */
function govt_atoz(){


	global $language,$base_url;
    $sel = 'All';
    $output = '';
	db_set_active('cmsdb');
		//drupal_add_css(drupal_get_path('module', 'go_view') . 'css/go_view.css');
		$op = get_govt_header( 'atoz' );
		$op .= "<div class='result_inner'><div class='view-header'>" . Govt_AtoZ_letters( $sel ) . "</div>";
		$op .= "<div class='go_view'><div class='back_btn'><span>" .l(t('Back'),'go_view/atoz'). "</span></div>";

	$lan = array($GLOBALS['language']->language);

	$query = new EntityFieldQuery();
	$query->entityCondition('entity_type', 'node')
		  ->entityCondition('bundle', 'govt_orders')
		  ->propertyCondition('language', array($GLOBALS['language']->language, ''),'IN')
		  ->propertyCondition('status', 1)
		  ->fieldOrderBy('field_go_depart','value','ASC')
		  ->fieldOrderBy('field_go_date', 'value','DESC')
		 // ->addMetaData('account', user_load(1))
		  ->pager(20,0);


	$result = $query->execute();

	if (isset($result['node'])) {

	  $news_items_nids = array_keys($result['node']);
	  //$items = entity_load('node', $news_items_nids);

	 // print "<pre>"; print_r($items); print "</pre>";die;

	 }

	db_set_active('default');
        $curdept = '';
		$go_year = '';
		$kbyte = '';
		foreach ($news_items_nids as $nid){
			my_db_change(1);
			$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
			$res = node_load($nid, $vid);
			$go_date = go_view_get_date($nid, $vid);
			my_db_change(0);

	//echo "Muthukkumar";
	//print "<pre>"; print_r($res); print "</pre>";

		$dept =  $res->field_go_depart['und']['0']['value'];
		$deptName = get_govt_dept_names($dept);

		$abstract =  $res->field_go_abstract['und']['0']['value'];
		$filepath = $res->field_go_available_file['und']['0']['uri'];
		$filesize = $res->field_go_available_file['und'][0]['filesize'];
		$title = $res->title;


		$go_date_check = date('F d, Y',strtotime($go_date));
		$goYear = date("Y", strtotime($go_date));

	if(empty($filepath)){
							$wrapper = file_stream_wrapper_get_instance_by_uri($res->field_go_available_file['und']['0']['uri']);

							if($wrapper == true){
								$filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($res->field_go_available_file['und']['0']['uri']);
							}
							$icon = '';
					}else{
						  	$icon = get_pdf_icon($filesize)	;
						 	//$filepath = $baseurl.$contentlist->filepath;
							$wrapper = file_stream_wrapper_get_instance_by_uri($res->field_go_available_file['und']['0']['uri']);

							if($wrapper == true){
								$filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($res->field_go_available_file['und']['0']['uri']);

							}//$department= $contentlist -> dept_name;

					}

					if($res->field_go_available_file['und']['0']['filesize'] != 0){

							$kb = ceil($res->field_go_available_file['und'][0]['filesize']/1024);
						$kbyte= $kb.KB;
						if($kb >1024) {
						  $kb = ceil($kb/1024);
						  $kbyte= $kb.MB;
						}
					}

		if( $goYear != $go_year )		{
					$go_year = $goYear;
					$divOutput1 = "<div class='res_dept go_depart' ><strong>Year : " .  $goYear  . "</strong></div>";
				}
				else		{
					$divOutput1 = '';
				}

		if( $deptName != $curdept )		{
			$curdept = $deptName;
			$divOutput =   $deptName ;

		}
		else{
			$divOutput = '';
		}



	$op .= "<div class='go_box'>
				<div class='res_dept go_depart'><span><strong>" .$divOutput. "</strong></span></div>
								<div class='go_title'>" .$divOutput1. "</div>

				<div class='go_abstract'><a target='_blank' href='http://cms.tn.gov.in/tncms_latest/" .$filepath. "'>"
				.$title . " Dt: ". $go_date_check."<span class='kb'>". $icon. $kbyte. "</span></a>"
				   .$abstract. "</div>
			</div>";

	}

	//$output .= "<div id='result_go' class='result_inner'>";
	$output .= $op;
	//$output .= "<div class='clr'></div></div>";




	return $output.theme('pager');
	//theme('gos_atoz', array('items' => $items)). theme('pager');
}

/**
 * Function for govt_atoz_letter()
 * @return string
 */
function govt_atoz_letter() {

	global $base_url,$language;

	$let_val = strtolower(arg(2));
    $output = '';


	db_set_active('cmsdb');
		//drupal_add_css(drupal_get_path('module', 'go_view') . 'css/go_view.css');
		$op = get_govt_header( 'atoz' );
		$op .= "<div class='result_inner'><div class='view-header'>" . Govt_AtoZ_letters( $let_val ) . "</div>";
		$op .= "<div class='go_view'><div class='back_btn'><span>" .l(t('Back'),'go_view/dept'). "</span></div>";

	$lan = array($GLOBALS['language']->language);

	if($let_val !='all') {

		$query = new EntityFieldQuery();
		$query->entityCondition('entity_type', 'node')
			  ->entityCondition('bundle', 'govt_orders')
			  ->propertyCondition('language', array($GLOBALS['language']->language, ''),'IN')
			  ->propertyCondition('status', 1)
			  ->fieldCondition('field_go_abstract','value',$let_val.'%', "LIKE")
			  ->fieldOrderBy('field_go_depart', 'value','ASC')
			  ->fieldOrderBy('field_go_date', 'value','DESC')
			  ->pager(20,0);
	}
	else {

		$query = new EntityFieldQuery();
		$query->entityCondition('entity_type', 'node')
		  ->entityCondition('bundle', 'govt_orders')
		  ->propertyCondition('language', array($GLOBALS['language']->language, ''),'IN')
		  ->propertyCondition('status', 1)
		  ->fieldOrderBy('field_go_depart', 'value','ASC')
		  ->fieldOrderBy('field_go_date', 'value','DESC')
		  ->pager(20,0);
	}

	$sql = $query->execute();


	if (isset($sql['node'])) {
	  $news_items_nids = array_keys($sql['node']);
	  //$val = entity_load('node', $news_items_nids);
	 // print "<pre>"; print_r($items); print "</pre>";die;
	}

	db_set_active('default');
    $go_year = '';
	$curdept = '';
	$kbyte = '';
	foreach ($news_items_nids as $nid){
		my_db_change(1);
		$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
		$res = node_load($nid, $vid);
		$go_date = go_view_get_date($nid, $vid);
		my_db_change(0);
	//echo "Muthukkumar";
	//print "<pre>"; print_r($res); print "</pre>";

		$dept =  $res->field_go_depart['und']['0']['value'];
		$deptName = get_govt_dept_names($dept);
		$abstract =  $res->field_go_abstract['und']['0']['value'];
		$filepath = $res->field_go_available_file['und']['0']['uri'];
		$filesize = $res->field_go_available_file['und'][0]['filesize'];
		$title = $res->title;

		//$go_date = $res->field_go_date['und']['0']['value'];
		//echo $Year = $go_date->format('d-m-Y');
		$go_date_check = date('F d, Y',strtotime($go_date));
		$goYear = date("Y", strtotime($go_date));

		if(empty($filepath)){
							$wrapper = file_stream_wrapper_get_instance_by_uri($res->field_go_available_file['und']['0']['uri']);

							if($wrapper == true){
								$filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($res->field_go_available_file['und']['0']['uri']);
							}
							$icon = '';
					}else{
						  	$icon = get_pdf_icon($filesize)	;
						 	//$filepath = $baseurl.$contentlist->filepath;
							$wrapper = file_stream_wrapper_get_instance_by_uri($res->field_go_available_file['und']['0']['uri']);

							if($wrapper == true){
								$filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($res->field_go_available_file['und']['0']['uri']);

							}//$department= $contentlist -> dept_name;

					}

					if($res->field_go_available_file['und']['0']['filesize'] != 0){

						$kb = ceil($res->field_go_available_file['und'][0]['filesize']/1024);
						$kbyte= $kb.KB;
						if($kb >1024) {
						  $kb = ceil($kb/1024);
						  $kbyte= $kb.MB;
						}
					}


		if( $goYear != $go_year )		{
					$go_year = $goYear;
					$divOutput1 = "<div class='res_dept go_depart' ><strong>Year : " .  $goYear  . "</strong></div>";
				}
				else		{
					$divOutput1 = '';
				}

		if( $deptName != $curdept )		{
			$curdept = $deptName;
			$divOutput =   $deptName ;

		}
		else{
			$divOutput = '';
		}



	$op .= "<div class='go_box'>
				<div class='res_dept go_depart'><span><strong>" .$divOutput. "</strong></span></div>
								<div class='go_title'>" .$divOutput1. "</div>

				<div class='go_abstract'><a target='_blank' href='http://cms.tn.gov.in/tncms_latest/" .$filepath. "'>"
				.$title . " Dt: ". $go_date_check."<span class='kb'>". $icon.$kbyte."</span></a>"
				   .$abstract. "</div>
			</div>";

	}

	//$output .= "<div id='result_go' class='result_inner'>";
	$output .= $op;
	//$output = $docheader. theme('gos_atoz_letter', array('result' => $val)). theme('pager');
	return $output.theme('pager');
}

function govt_department() {

	global $base_url,$language;
	$output = '';

	db_set_active('cmsdb');

	//drupal_add_css(drupal_get_path('module', 'go_view') . 'css/go_view.css');
	$op = "<div id='viewmod_govtinterest' class='view-header'>" . get_govt_header( 'dept' ) ."</div>";

	//print_r($result);
	$qry = db_select('depart_mst','d');
		$qry->fields('d',array('dep_id','dept_name'))->distinct();
		$qry->addJoin('INNER','field_data_field_go_depart','gd', 'd.dep_id = CAST(gd.field_go_depart_value AS INT)');
		$qry->condition('n.status', 1);
		$qry->condition('n.language', array($GLOBALS['language']->language),'=');
		$qry->addJoin('INNER','node','n','n.nid = gd.entity_id' );
		$qry->orderby('d.dep_id','ASC');

	//print $qry;
	$result = $qry->execute();
	db_set_active('default');

	foreach($result as $res){

			if($language->language == 'en'){
			 	$op .= "<div class='go_view_dept_list'> <p>" .l(t($res->dept_name), 'go_view/dept/' . $res->dep_id) . "</p> </div>" ;
			}else{
				$op .= "<div class='go_view_dept_list'> <p>" .l(t($res->dept_name), 'ta/go_view/dept/' . $res->dep_id) . "</p> </div>" ;
			}

	}

	$output .= "<div id='result_go' class='result_inner'>";
	$output .= $op;
	$output .= "<div class='clr'></div></div>";


	return $output;

}



function go_search_form() {
	//drupal_add_css(drupal_get_path('module', 'go_view') . '/go_view.css');
	//$modPath = drupal_get_path('module', 'go_view');
	drupal_set_title(t('Government of Tamil Nadu')." : ".t('Government Orders'));
	$output = '';
	//unset_search_session('go_keyword');
	//variable_set('go_search_word', '');
	$docheader = get_govt_header( '' );
	$docheader = "<div id='viewmod_govtinterest' class='view-header'>" . get_govt_header( 'find' ) ."</div>";
	$StrOp = "<div class='result_inner' id='result_go'><div class='go_view'>";
	$StrEnd = "<div class='clr'></div></div><div class='clr'></div></div>";
	$form = drupal_get_form('go_search');
	$output .=  $docheader.$StrOp . drupal_render($form).$StrEnd;
	return $output;
}

function go_search($form_state){
	$keyword = trim(arg(2));
	$form['go_search'] = array(
	'#type' => 'textfield',
	'#title' => t('Keyword'),
	'#default_value' => $keyword ? $keyword : '',
	'#size'=>'35',
	'#prefix' => '<div class="keyword_go">',
	'#description'=>'<div class="keyword_go_descr"> Ex: G.O.Ms.No.42 OR Medical Education',
	);

    $form[ 'go_submit' ] = array(
	'#title' => 'Submit',
	'#type' => 'submit',
	'#value' => 'Go',
	'#name' => 'search',
	'#prefix' => '<div class="sea_go_but">',
	'#suffix' => '</div></div>',

	);
	return $form;

}

/**
 * function for hook_validate()
 * @param unknown_type $form
 * @param unknown_type $form_state
 */
function go_search_validate($form, &$form_state) {
  $formValues = $form_state['values']['go_search'];
  if (empty($formValues)) {
    //form_set_error('', t('Please Enter Key Word'));
  }
}

function go_search_submit($form,&$form_state){
	global $base_url;
	$str = $form_state['values']['go_search'];
    if (empty($str)) {
      form_set_error('', t('Please Enter Key Word'));
    }
	$form_state['redirect'] = 'go_view/searchresult/'.$str;
	return;

}

/**
 * Function for go_search_form_result()
 * @return string
 */
function go_search_form_result(){
	global $base_url,$language;
	//print $base_url; exit;

        $op = '';
        $output = '';
        $news_items_nids = array();
        $gt_news_items_nids = array();

		//drupal_add_css(drupal_get_path('module', 'go_view') . '/go_view.css');
		$docheader = "<div id='viewmod_govtinterest' class='view-header'>" . get_govt_header( 'find' ) ."</div>";
		//$op = get_govt_header( '' );
		$form = drupal_get_form('go_search');
		$docheader .= drupal_render($form);

	//$op .= "<div class='go_view'><div class='back_btn'><span>" .l(t('Back'),'go_view/dept'). "</span></div>";
		$str = strtoupper(trim(arg(2)));


			  //echo $keyword.''.chkbadcharportal($keyword);
			  /*if(chkbadcharportal($str)== FALSE){

					form_set_error('Keywords', t('Keyword field contains bad characters'));
					 drupal_goto('go_view/searchresult');
			 }*/

		$go_keyword= trim(arg(2));
		$go_keyword= strtolower($go_keyword);
		//$ser_string = array();
		$go_keyword = preg_replace('/[\p{Z}\s]{2,}/u', ' ', $go_keyword);
		$go_keyword=pg_escape_string($go_keyword);
        /*
		$len = drupal_strlen($go_keyword);
		$keyword1 =$go_keyword;


			// Do not count UTF-8 continuation bytes.
		 if(!empty($keyword1))
		 {
		$position[0]=strpos($keyword1,'"');

		 if($position[0] != "");{

		  $position[1]=strpos($keyword1,'"',$position[0]+1);

		  }
		  }
		 if(!empty($position[1]))
		 {
			//echo substr($keyword,1)."</br>";
			$k=0;
			for($i=0;$i<=$len;$i++)
			{

			$position[0]=strpos($keyword1,'"');

			if(strlen($keyword1) !=0)
			{
			if($position[0] !=0 && $position[0] !="")
			$str_not_quote[$k++] =substr($keyword1,0,$position[0]);
			if($position[0] ==false)
			$str_not_quote[$k++] =substr($keyword1,0,strlen($keyword1));
			}


			 $position[1]=strpos($keyword1,'"',$position[0]+1);

			 if(empty($position[1]))
			 {
			 break;
			 }
			 $sub_string_len = $position[1] - $position[0]-1;

		 $ser_string[$i] = substr($keyword1,$position[0]+1, $sub_string_len);

			 $part_string= substr($keyword1,$position[1]+1, $len);

			$keyword1 =trim($part_string);
			if(empty($keyword1))
			{
			break;
			}
			}
			}
			$ser_string = array_filter_customize($ser_string);
			//print_r($ser_string);
			if(!empty($ser_string))
			{

				$sql_search_clause = search_keyword('LOWER(n.title)', $ser_string, $str_not_quote);
				$sql_search_clause .= "or ";
				$sql_search_clause .= search_keyword('LOWER(g.field_go_abstract_value)', $ser_string, $str_not_quote);
			}
			*/

	if($go_keyword==''){
		//$op = "<div class ='go_box'><strong>" .'Please Enter The Keyword'. "</strong></div>" ;
		$docheader = get_govt_header( '' );
		$StrOp = "<div class='result_inner' id='result_go'><div class='go_view'>";
		$StrEnd = "<div class='clr'></div></div><div class='clr'></div></div>";
		$form = drupal_get_form('go_search');
		$output =  $docheader.$StrOp . drupal_render($form).$StrEnd;
		return $output;
	}
	$go_val = $go_keyword;
	db_set_active('cmsdb');

	/*
	$query = db_select('node', 'n');
		$query->fields('n', array('title'));
		//$query->condition('n.type', 'govt_orders');
		$query->condition('n.status', '1');
		$query->condition('n.language', 'en');

		$query->addJoin('INNER','field_data_field_go_abstract', 'abs', 'n.nid = abs.entity_id');
		$query->addJoin('INNER','field_data_field_go_date', 'gd', 'n.nid = gd.entity_id');
		$query->join('file_usage', 'fu','n.nid = fu.id');
		$query->join('file_managed', 'fm','fm.fid = fu.fid' );
		$query->addField('gd','field_go_date_value');
		$query->addField('abs','field_go_abstract_value');
		$query->addField('fm','uri');
		$query->addField('fm','filesize');

		$conditions = db_or();
			$conditions->condition('n.title', $go_val.'%','LIKE');
         	$conditions->condition('abs.field_go_abstract_value', $go_val.'%','LIKE');
       $query->condition($conditions);


		//$query->condition('n.title', 'G.O.Ms.No.42%','LIKE');

		//print $query;
		$query->orderBy('gd.field_go_date_value', 'desc');

		//$result = $query->execute();
		$result = $query->extend('PagerDefault')->limit(20)->execute();
		$row_count = $result->rowCount();
		*/

		$lan = array($GLOBALS['language']->language);
		// Search by title
		$gt_query = new EntityFieldQuery();
		$gt_query->entityCondition('entity_type', 'node')
			->entityCondition('bundle', 'govt_orders')
			->propertyCondition('status',1)
			->propertyCondition('title', "%".$go_val."%","LIKE")
			->fieldOrderBy('field_go_date', 'value', 'DESC')
			->propertyCondition('language', array($GLOBALS['language']->language, ''),'IN')
			->pager(20);
		$gt_result = $gt_query->execute();

		if (isset($gt_result['node'])) {
			$gt_news_items_nids = array_keys($gt_result['node']);
		}
		// Search by abstract
		$query = new EntityFieldQuery();
		$query->entityCondition('entity_type', 'node')
			->entityCondition('bundle', 'govt_orders')
			->propertyCondition('status',1)
			->fieldCondition('field_go_abstract', 'value', "%".$go_val."%","LIKE")
			->fieldOrderBy('field_go_date', 'value', 'DESC')
			->propertyCondition('language', array($GLOBALS['language']->language, ''),'IN')
			->pager(20);
		$result = $query->execute();

		if (isset($result['node'])) {
			$news_items_nids = array_keys($result['node']);
		}

		// Merge Go Title and abstract Results:
		$news_items = array_merge( (count($gt_news_items_nids) == 0) ? array() : $gt_news_items_nids, (count($news_items_nids) == 0) ? array() : $news_items_nids);
		my_db_change(0);

		//print_r($result);
		db_set_active('default');
		$row_count = count($news_items);

		if($news_items==''){
			$val = "<div class ='go_box'><strong>" .'No record Found'."</strong></div>";
		}
		else{
			$val = "<div class ='go_box'><strong>" .$row_count .'  record Found' . "</strong></div>";
		}

      $kbyte = '';
      $goYear = '';
      $go_year = '';
	foreach($news_items as $nid) {
		my_db_change(1);
		$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
		$res = node_load($nid, $vid);
		$go_date = go_view_get_date($nid, $vid);
		my_db_change(0);

		 //print "<pre>"; print_r($res); print "</pre>";

		$dept = $res->field_go_depart['und'][0]['value'];
		$deptName = get_govt_dept_names($dept);
		$abstract =  $res->field_go_abstract['und'][0]['value'];
		$filepath = $res->field_go_available_file['und'][0]['uri'];
		$filesize = $res->field_go_available_file['und'][0]['filesize'];
		$title = $res->title;

		$go_date_check = date('F d, Y',strtotime($go_date));
		$goYear = date("Y", strtotime($go_date));

	if(empty($filepath)){
							$wrapper = file_stream_wrapper_get_instance_by_uri($filepath);

							if($wrapper == true){
								$filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($filepath);
							}
							$icon = '';
					}else{
						  	$icon = get_pdf_icon($filesize)	;
						 	//$filepath = $baseurl.$contentlist->filepath;
							$wrapper = file_stream_wrapper_get_instance_by_uri($filepath);

							if($wrapper == true){
								$filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($filepath);

							}//$department= $contentlist -> dept_name;

					}

					if($filesize != 0){

							$kb = ceil($filesize/1024);
						$kbyte= $kb.KB;
						if($kb >1024) {
						  $kb = ceil($kb/1024);
						  $kbyte= $kb.MB;
						}
					}

		if( $goYear != $go_year )		{
					$go_year = $goYear;
					$divOutput1 = "<div class='res_dept go_depart' ><strong>Year : " .  $goYear  . "</strong></div>";
				}
				else		{
					$divOutput1 = '';
				}
        $curdept = '';

		if( $deptName != $curdept )		{
			$curdept = $deptName;
			$divOutput =   $deptName ;

		}
		else{
			$divOutput = '';
		}



	$op .= "<div class='go_box'>
				<div class='res_dept go_depart'><span><strong>" .$divOutput. "</strong></span></div>
								<div class='go_title'>" .$divOutput1. "</div>
				<div>" . $res->nid ."</div>
				<div class='go_abstract'><a target='_blank' href='http://cms.tn.gov.in/tncms_latest/" .$filepath. "'>"
				.$title . " Dt: ". $go_date_check."<span class='kb'>". $icon. $kbyte. "</span></a>"
				   .$abstract. "</div>
			</div>";

	}


		$head = get_govt_header( '' );
		$form = drupal_get_form('go_search');
		$head1 = drupal_render($form);
		$StrOp = "<div class='result_inner' id='result_go'><div class='go_view'>";
		$StrEnd = "<div class='clr'></div></div><div class='clr'></div></div>";
		$output .= $head. $StrOp.$head1.$val.$op.$StrEnd;


	return $output. theme('pager');

}

function go_view_query_alter($query) {
if ($query->hasTag('debug')) {
dpq($query);
}
}

function get_govt_dept_names($ids) {

	db_set_active('cmsdb');
	 	$qry = db_select('depart_mst','d')
			->fields('d',array('dep_id','dept_name'))
  			->condition('dep_id', $ids)
			->execute();
		foreach($qry as $result) {

	 		$dept_name = $result->dept_name;
		}
	db_set_active('default');

	return $dept_name;
}


function get_govt_header( $css )
{
	global $base_url;
	 if($css=='atoz'){ $atoz= "view_head_sel";}else {$atoz= "view_head_nonsel";}
     if($css=='dept') { $dept="view_head_sel"; }else{ $dept='view_head_nonsel'; }
     if($css=='find') { $find="view_head_sel"; }else {$find='view_head_nonsel'; }


	global $language;
	if($language->language=='ta'){
		$css='govtinterest_ta';

		$html = "<div class='view-header' id='viewmod_$css'>
		<div class='inner_tab_content'>
		<div class='inner_li'>".l(t('Department wise'),'ta/go_view/dept')."</div>
		<div class='inner_li'>".l(t('Search'),'ta/go_view/search')."</div>
		<div class='inner_li'>".l(t('A to Z'),'ta/go_view/atoz')."</div>
		<div class='clr'></div></div>
	</div>";

	}
	else{
		$css='govtinterest';


	$html = "<div class='view-header' id='viewmod_$css'>
		<div class='inner_tab_content'>
		<div class='inner_li'>".l(t('Department wise'),'go_view/dept')."</div>
		<div class='inner_li'>".l(t('Search'),'go_view/search')."</div>
		<div class='inner_li'>".l(t('A to Z'),'go_view/atoz')."</div>
		<div class='clr'></div></div>
	</div>";
	}
	return $html;
}

?>